package cn.com.dhcc.turbo.web.controller.sysmgr;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.annotation.SiNoNeedLogin;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.service.MailServiceImpl;
import cn.com.dhcc.app.core.util.FreemarkerUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.turbo.entity.registry.AdapterInfo;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfoExt;
import cn.com.dhcc.turbo.service.registry.AdapterInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.sysmgr.UserMgrService;

@Controller
@RequestMapping("usermgr")
@TurboMenu(belongToMenu=LEAF_MENU.USER_MGR)
public class UserMgrController extends BaseController{
	private Logger logger = Log.getLogger(LOGTYPE.TURBO);
	
	@Autowired
	UserMgrService userMgrService;
	@Autowired
	private NodeInfoService nodeService;
	@Autowired
	private MailServiceImpl mailService;
	@Autowired
	AdapterInfoService adapterService;
	/**
	 * 用户列表
	 * @param model
	 * @param httpSession
	 * @param sysId
	 * @return
	 */
	@RequestMapping("user_list")
	public String userList(Model model,HttpSession httpSession, Pager pager,String userType,String ownId){
		try {
			List<AdapterInfo> adapterList = adapterService.getLocalAdapterList();
			UserInfo user = (UserInfo)getCurrentUserInfo(httpSession);
			WhereCondition condition = new WhereCondition();
			condition.where().notEq("t.user_name", "admin");
			if(!"".equals(ownId) && ownId != null){
				condition.and().eq("t.own_id", ownId);
			}
			if(!"".equals(userType) && userType != null){
				condition.and().eq("t.user_type", userType);
			}
			condition.orderBy("t.user_type desc,t.mtime desc");
			if(user != null){
				PagerData<UserInfo> pagerData = userMgrService.list(pager,condition);
				model.addAttribute("sysUsers", pagerData.getDatas());
				setTotoal(model, pagerData.getTotal());
			}
			NodeInfo nodeInfo = nodeService.getLocalNode();
			model.addAttribute("nodeInfo", nodeInfo);
			model.addAttribute("adapterList", adapterList);
		} catch (ServiceException e) {
			return toAlertPage(model, e.getMessage());
		}
		return "sysmgr/user_list";
	}
	/**
	 * 重置密码
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("reset_pwd/{id}")
    public Map<String, Object> resetPassword(@PathVariable String id) {
		String newPwd ;
        try {
        	newPwd = userMgrService.resetPwdByUserId(id);
        } catch (Exception e) {
            return jsonFailResult("重置密码失败");
        }
        return jsonSuccessResult("重置成功，新密码为:"+newPwd);
    }
	/**
	 * 用户添加
	 * @param model
	 * @return
	 */
	@RequestMapping("user_add")
	public String userAdd(Model model){
		try {
			NodeInfo nodeInfo = nodeService.getLocalNode();
			List<AdapterInfo> adapterList = adapterService.getLocalAdapterList();
			model.addAttribute("adapterList", adapterList);
			model.addAttribute("nodeId", nodeInfo.getId());
			return "sysmgr/user_add";
		} catch (ServiceException e) {
			return toAlertPage(model, e.getMessage());
		}
	}
	/**
	 * 添加用户
	 * @param model
	 * @param vo
	 * @param pwd2
	 * @return
	 */
	@RequestMapping(value = "/add_user", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUser(Model model, UserInfo vo,String pwd2) {
		try {
			if(pwd2.equals(vo.getPwd())){
				vo.setId(UUIDGenerator.getUUID());
				vo.setMtime(new Date());
				userMgrService.insertOrUpdateUser(vo);
				return jsonSuccessResult("添加用户成功");
			}else{
				return jsonFailResult("密码和确认密码输入不一致,请确认！");
			}
		} catch (Exception e) {
			return jsonFailResult("添加用户失败");
		}
	}
	/**
	 * 用户信息修改
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("user_update/{id}")
	public String userUpdate(Model model,@PathVariable String id){
		try {
			UserInfo userinfo = userMgrService.get(id);
			model.addAttribute(DATA_KEY, userinfo);
			return "sysmgr/user_update";
		} catch (ServiceException e) {
			return toAlertPage(model, e.getMessage());
		}
	}
	/**
	 * 修改用户
	 * @param model
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/update_user", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update_user(Model model, UserInfo vo) {
		try {
				vo.setMtime(new Date());
				userMgrService.insertOrUpdateUser(vo);
				return jsonSuccessResult("修改用户成功");
		} catch (Exception e) {
			return jsonFailResult("修改用户失败");
		}
	}
	/**
	 * 删除用户（真删）
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/user_delete")
	@ResponseBody
	public Map<String, Object> deleteById(String id, Model model) {
		try {
			userMgrService.deleteUser(id);
			return jsonSuccessResult("删除用户成功");
		} catch (ServiceException e) {
			return jsonFailResult("删除用户失败");
		}
	}
	/**
	 * 加载找回密码申请页
	 * @return
	 */
	@RequestMapping("/user_find_pwd")
	@SiNoNeedLogin
	public String UserFindPwd(){
		
		return "sysmgr/user_find_pwd";
	}
	/**
	 * 发送找回密码申请，发送找回密码邮件
	 * @param userName
	 * @param email
	 * @param model
	 * @return
	 */
	@RequestMapping("/find_pwd_user")
	@SiNoNeedLogin
	@ResponseBody
	public Map<String, Object> findPwdUser(String userName,String email, Model model) {
		try {
			UserInfo user = userMgrService.getByuserNameAndEmail(userName,email);
			if(user == null){
				return jsonFailResult("用户信息错误，请确认！");
			}
			UserInfoExt vo= new UserInfoExt();
			vo.setId(UUIDGenerator.getUUID());
			vo.setUserId(user.getId());
			vo.setMtime(new Date());
			vo.setStatus("1");
			userMgrService.addUserExt(vo);
			Map<String, Object> rootMap = new HashMap<String, Object>();
			NodeInfo node = nodeService.getLocalNode();
			String file = this.getClass().getResource("/template/findpwd/email_to_findpwd.flt").getFile();
			String url =  node.getInstallUrl()+"/usermgr/find_pwd/"+vo.getId()+".do";
			rootMap.put("url", url);
			String content = FreemarkerUtil.flushData(file, rootMap);
			mailService.sendHtmlEmail(user.getEmail(), "数据交换平台找回密码", content, "", null);
			return jsonSuccessResult(user.getEmail());
		} catch (Exception e) {
			return jsonFailResult("找回密码申请失败");
		}
	}
	/**
	 * 加载设置新密码页（找回密码）
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/find_pwd/{id}")
	@SiNoNeedLogin
	public String findPwd(Model model,@PathVariable String id){
		try {
			UserInfoExt userExt = userMgrService.getByuserExtByid(id);
			if(userExt == null){
				model.addAttribute("Errmsg", "您的找回密码链接已经失效，请重新申请！");
				return "sysmgr/user_find_pwd";
			}
			Date date = new Date();
			long today = date.getTime();
			long mtime =  userExt.getMtime().getTime();
			if((today - mtime)/(1000*60*60) > 24){
				model.addAttribute("Errmsg", "您的找回密码链接已过期，请重新申请！");
				return "sysmgr/user_find_pwd";
			}
			model.addAttribute("extId", id);
		} catch (ServiceException e) {
			logger.error(e);
		}
		return "sysmgr/reset_pwd";
	}
	/**
	 * 设置新密码，删除找回密码申请
	 * @param extId
	 * @param pwd
	 * @param model
	 * @return
	 */
	@RequestMapping("/resetpwd")
	@SiNoNeedLogin
	@ResponseBody
	public Map<String, Object> resetPwd(String extId,String pwd, Model model) {
		try {
			UserInfoExt userExt = userMgrService.getByuserExtByid(extId);
			Date date = new Date();
			if(userExt == null || (date.compareTo(userExt.getMtime()) )>1000*60*60*24){
				return jsonFailResult("信息错误，请重新申请！");
			}
			UserInfo vo = userMgrService.get(userExt.getUserId());
			vo.setPwd(pwd);
			userMgrService.insertOrUpdateUser(vo);
			userMgrService.deleteUserExt(extId);
			return jsonSuccessResult("密码已重置，请使用新密码登录！");
		} catch (ServiceException e) {
			return jsonFailResult("找回密码失败");
		}
	}
	/**
	 * 验证用户名唯一性
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("/is_username_unique")
	@ResponseBody
	public String isUserNameUnique(@RequestParam("userName") String newValue,@RequestParam("oldValue") String oldValue) {
		try {
			if (userMgrService.isPropertyUnique( "user_name",newValue, oldValue)) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (Exception e) {
			return FORM_CHECK_FAIL;
		}
	}
	/**
	 * 验证邮箱唯一性
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("/is_email_unique")
	@ResponseBody
	public String isEmailUnique(@RequestParam("email") String newValue,@RequestParam("oldValue") String oldValue) {
		try {
			if (userMgrService.isPropertyUnique("email" ,newValue, oldValue)) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (Exception e) {
			return FORM_CHECK_FAIL;
		}
	}
}
